package com.xunyu.shopping_manager_api.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.xinyu.shopping_common.entity.Admin;
import com.xinyu.shopping_common.enums.CodeEnum;
import com.xinyu.shopping_common.result.BaseResult;
import com.xinyu.shopping_common.service.IAdminService;
import com.xunyu.shopping_manager_api.service.ILoginService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class LoginServiceImpl implements ILoginService {


    @DubboReference
    private IAdminService adminService;

    @Override
    public BaseResult login(String username, String password) {
        //1.根据账号查询用户是否存在
        Admin admin = adminService.findByAdminName(username);

        //账号存在
        if (Objects.nonNull(admin)) {
            String md5 = SaSecureUtil.md5(password);
            //2.比对密码
            if (md5.equals(admin.getPassword())){
                //使用sa-token框架登录
                StpUtil.login(username);

                //获取登录令牌
                String tokenValue = StpUtil.getTokenValue();
                //登录成功，返回token给前端
                return BaseResult.success(tokenValue);
            }
        }
        return BaseResult.error(CodeEnum.LOGIN_ERROR.getCode(), CodeEnum.LOGIN_ERROR.getMessage());
    }
}
